/* Utilities.java
 * Author: liuex
 * 2007-12-19 ����05:43:29
 *
 * Note: 
 */
package lex.proxyverfier.verifier;

import java.io.InputStream;

/**
 * ����InputStream�Ķ����ٶȣ���λ���ֽ�/��.<br>
 * ���Խ����Լ��������������κ�һ���󣬶���ֹͣ�������������ٶ�Ȼ�󷵻�: 1.
 * �ﵽInputStream���յ�; 2. �ﵽmaxLength,����������ֽ���; 3.
 * �ﵽmaxMillis,�������ʱ��.
 */
public class SpeedCalculator {
	private static final int DEFAULT_BUFFER_SIZE = 512;
	private static final long DEFAULT_MILLIS = 6000;
	private byte[] buffer = null;
	private long maxLength = 1024 * 1024;
	private long maxMillis = 5000;
	private boolean stop = false;

	public SpeedCalculator() {
		this(DEFAULT_BUFFER_SIZE, 5 * 1024 * 1024, DEFAULT_MILLIS);
	}

	public SpeedCalculator(int maxMillis) {
		this(DEFAULT_BUFFER_SIZE, 5 * 1024 * 1024, maxMillis);
	}

	public SpeedCalculator(int bufsize, long maxLength, long maxMillis) {
		this.buffer = new byte[bufsize];
		this.maxLength = maxLength;
		this.maxMillis = maxMillis;
	}

	/**
	 * 
	 * @param in
	 *            ��Ҫ���ٵ���
	 * @return �����ٶȣ���λ���ֽ�/�룬���߷���-1������쳣
	 */
	public long calculateSpeed(InputStream in) {

		if (null == in)
			return -1L;
		ThreadPool.execute(new Runnable() {
			public void run() {
				try {
					Thread.sleep(maxMillis);
				} catch (Exception e) {
				} finally {
					stop = true;
				}
			}
		});
		long startTime = System.currentTimeMillis();
		long count = 0;
		int len = 0;
		while (false == stop) {
			try {
				len = in.read(buffer);
			} catch (Exception e) {
				break;
			}
			if (-1 == len)
				break;
			else
				count += len;
			if (count >= this.maxLength)
				break;
		}
		long time = System.currentTimeMillis() - startTime;
		if (0 == time)// this couldn't happen, i thought...
			return -1L;
		return count * 1000 / time;
	}
}
